/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月18日         Root.Lu
 */

package com.coocaa.x.framework.app;

import android.content.Context;
import android.util.Log;

import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.FansChannelUpgrade;
import com.coocaa.x.framework.utils.FansChannelUpgrade.PojieSwitchData;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.skyworth.framework.skysdk.android.SkySystemUtil;
import com.skyworth.webSDK.factory.WebComplexFactory;
import com.skyworth.webSDK.factory.WebSimpleFactory;
import com.skyworth.webSDK.factory.XWebComplexFactory;
import com.skyworth.webSDK.utils.EntryPointEnum;
import com.skyworth.webSDK.webservice.RestClient;
import com.skyworth.webSDK.webservice.XRestClient;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreServiceImpl;
import com.skyworth.webSDK.webservice.tcappstore.GPushWebService;
import com.skyworth.webSDK.webservice.weather.service.WeatherService;

public class CoocaaWebService {
    private AppStoreServiceImpl appstore = null;
    private WeatherService weatherService = null;

    private GPushWebService pushService = null;
    private WebComplexFactory wcf = null;
    private Thread thread = null;

    public synchronized void init() {
        if (thread == null) {
            thread = new Thread("CoocaaWebService init Thread") {
                @Override
                public void run() {
                    synchronized (CoocaaWebService.this) {
                        _init();
                        thread = null;
                        CoocaaWebService.this.notify();
                    }
                }
            };
            thread.start();
        }
    }

    protected void _init() {
        Context mContext = CoocaaApplication.getContext();
        String server = (String) Android.getMetaData(mContext, mContext.getPackageName(), "SERVER");
//        String channel = fixChannel(CoocaaApplication.getContentChannel(),server);
        String channel = getContentChannel(server);
        String deviceID = CoocaaApplication.getMAC();
        String session = "";
        try {
            session = XServiceManager.getLiteUserService().getSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (session == null || session.equals(""))
            session = "00dd5ca1626de5733c0a06932834a098-forold";
        LogUtils.d("test", "create  " + channel + " " + deviceID + " " + session + " " + server);
        XRestClient.setSdkver(String.valueOf(android.os.Build.VERSION.SDK_INT));
        XRestClient.setGamecenter_channel("SkyGames");
        XRestClient.setChannel(channel);
        XRestClient.setTvinfo(deviceID);
        XRestClient.setSession(session);

        AppStoreServiceImpl.setGeneralPlatServer(server);
        appstore = (AppStoreServiceImpl) XWebComplexFactory.getInstance(server).getClassInstance(
                AppStoreServiceImpl.class.getName());
        appstore.setHttpMethod("POST");

        RestClient.setSession(session);
        weatherService = WebSimpleFactory.getInstance(EntryPointEnum.tvos).createWeatherService();
        weatherService.setHttpMethod("POST");

        wcf = WebComplexFactory.getInstance(server);
        pushService = new GPushWebService("push.tc.skysrt.com");
        // dev地址
        // appStore = (AppStoreServiceImpl) XWebComplexFactory.getInstance(
        // EntryPointEnum.dev.entryPoint() + ":8989/TCAppstore_INTERFACE/")
        // .getClassInstance(AppStoreServiceImpl.class.getName());

        // 测试地址
        // appstore = (AppStoreServiceImpl) XWebComplexFactory.getInstance(
        // "42.121.113.121" + ":8989/TCAppstore_INTERFACE/").getClassInstance(
        // AppStoreServiceImpl.class.getName());
    }

    private String fixChannel(String channel,String server) {
        if (!channel.equals("SkyFans")) {
            boolean fansFlag = FansChannelUpgrade.getFansFlag();
            if (!fansFlag) {
                if (FansChannelUpgrade.getDownloadcounts() && FansChannelUpgrade.getOpenstoretimes()) {
                    FansChannelUpgrade.setFansFlag(true);
                }else {
                    return channel;
                }
            }
            try {
                String json = FansChannelUpgrade.getPojieSwitchFromWeb(server);
                PojieSwitchData data = PojieSwitchData.parseJObject(json, PojieSwitchData.class);
                LogUtils.d("channel", "Switch:" + data.data);
                if (data.data)
                    return "SkyFans";
                else
                    return channel;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return channel;
    }

    private String getContentChannel(String server){

        if(SkySystemUtil.isBetaVersion()){
            CoocaaApplication.setContentChannel("SkyFans");
            return "SkyFans";
        }

        Context context = CoocaaApplication.getContext();
        boolean isFansApkInstalled = Android.isPackageInstalled(context, "com.developer.fans");
        boolean fansFlag = FansChannelUpgrade.getFansFlag();
        if(isFansApkInstalled || fansFlag){
            String channel1 = getChannelFromPojieSwitch(server);
            CoocaaApplication.setContentChannel(channel1);
            return channel1;
        }
//        if (!fansFlag) {
            if (FansChannelUpgrade.getDownloadcounts() && FansChannelUpgrade.getOpenstoretimes()) {
                FansChannelUpgrade.setFansFlag(true);
                String channel2 = getChannelFromPojieSwitch(server);
                CoocaaApplication.setContentChannel(channel2);
                return channel2;
            }
//        }

        String channel = (String) Android
                .getMetaData(context, context.getPackageName(), "CONTENT_CHANNEL");
        if (channel == null || channel.equals("")) {
            LogUtils.e("getContentChannel failed,ues SkyCoocaa instead!!");
            channel = "SkyCoocaa";
        }
        CoocaaApplication.setContentChannel(channel);
        return channel;
    }

    private String getChannelFromPojieSwitch(String server){
        try {
            String json = FansChannelUpgrade.getPojieSwitchFromWeb(server);
            FansChannelUpgrade.PojieSwitchData data = FansChannelUpgrade.PojieSwitchData.parseJObject(json, FansChannelUpgrade.PojieSwitchData.class);
            LogUtils.d("fans", "Switch:" + data.data);
            if (data.data)
                return "SkyFans";
            else
                return "SkyCoocaa";
        } catch (Exception e) {
            e.printStackTrace();
            return "SkyCoocaa";
        }
    }

    public AppStoreServiceImpl getAppStoreService() {
        synchronized (CoocaaWebService.this) {
            if (appstore == null)
                try {
                    CoocaaWebService.this.wait();
                } catch (InterruptedException e) {
                }
            return appstore;
        }
    }

    public WeatherService getWeatherService() {
        synchronized (CoocaaWebService.this) {
            if (weatherService == null)
                try {
                    CoocaaWebService.this.wait();
                } catch (InterruptedException e) {
                }
            return weatherService;
        }
    }

    public WebComplexFactory getWebComplexFactory() {
        synchronized (CoocaaWebService.this) {
            if (wcf == null)
                try {
                    CoocaaWebService.this.wait();
                } catch (InterruptedException e) {
                }
            return wcf;
        }
    }

    public GPushWebService getGPushWebService() {
        synchronized (CoocaaWebService.this) {
            if (pushService == null)
                try {
                    CoocaaWebService.this.wait();
                } catch (InterruptedException e) {
                }
            return pushService;
        }
    }
}
